package com.zhang.gulimall.search.service;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.zhang.gulimall.common.to.AttrTo;
import com.zhang.gulimall.common.to.es.SkuEsModel;
import com.zhang.gulimall.common.utils.R;
import com.zhang.gulimall.search.config.ElasticSearchConfig;
import com.zhang.gulimall.search.constant.EsConstant;
import com.zhang.gulimall.search.feign.ProductFeignService;
import com.zhang.gulimall.search.vo.MySearchResult;
import com.zhang.gulimall.search.vo.SearchParam;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchService {

    @Resource
    RestHighLevelClient client;

    @Resource
    ProductFeignService productFeignService;

    public MySearchResult search(SearchParam param) {

        // 返回
        MySearchResult result = null;

        // 查询请求
        SearchRequest searchRequest = buildSearchRequest(param);
        // 聚合请求
        SearchRequest aggRequest = buildAggRequest(param);

        try {
            // 响应
            SearchResponse search = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            SearchResponse agg = client.search(aggRequest, ElasticSearchConfig.COMMON_OPTIONS);
            // 解析响应数据
            result = buildSearchResult(search,agg, param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    // 构建搜索请求
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 查询:模糊查询 , 过滤(按照属性,分类,品牌,价格区间...)
         */
        // 1.构建bool查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 1.1 must 模糊查询
        if (!StringUtils.isEmptyOrWhitespaceOnly(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }
        // 1.2 filter 3级分类
        if (!StringUtils.isEmptyOrWhitespaceOnly(param.getCatalog3Id())) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 1.2 filter 品牌id
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 1.2 filter 有无库存
        if (param.isHasStock()) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.isHasStock()));
        }
        // 1.2 filter 价格区间
        if (!StringUtils.isEmptyOrWhitespaceOnly(param.getSkuPrice())) {
            RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("skuPrice");

            String[] s = param.getSkuPrice().split("_");

            if (s.length == 2) {
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            } else {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(s[0]);
                } else {
                    rangeQueryBuilder.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        // 1.2 filter 属性
        if (param.getAttrs() != null) {
//            List<String> ids = new ArrayList<>();
//            List<String> values = new ArrayList<>();
            String[] s = param.getAttrs().split(";");
            for (String s1 : s) {
                BoolQueryBuilder nestedQueryBuilder = new BoolQueryBuilder();
//                ids.add(s1.split("_")[0]);
//                values.add(s1.split("_")[1]);
                nestedQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", s1.split("_")[0]));
                nestedQueryBuilder.must(QueryBuilders.termQuery("attrs.attrValue", s1.split("_")[1]));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
//            nestedQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrId", ids));
//            nestedQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", values));

        }
        sourceBuilder.query(boolQueryBuilder);
//        if (param.getAttrs()!=null) {
//                // attrs=1_其他:安卓&attrs=2_5寸:1.5寸
//                BoolQueryBuilder nestedBoolBuilder = QueryBuilders.boolQuery();
//                String[] s = param.getAttrs().split("_");
//                String attrId = s[0];   // 检索的属性id
//                String[] attrValues = s[1].split(";");  // 这个属性检索用的值
//                nestedBoolBuilder.must(QueryBuilders.termQuery("attrs.attrId",attrId));
//                nestedBoolBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
//                // 每一个必须都得生成一个嵌入式的查询nested
//                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolBuilder, ScoreMode.None);
//            boolQueryBuilder.filter(nestedQuery);
//
//        sourceBuilder.query(boolQueryBuilder);
//        }
        /**
         *  排序,分页,高亮
         */
        // 2.1 排序
        if (!StringUtils.isEmptyOrWhitespaceOnly(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder sort = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], sort);
        }
        // 2.2 分页
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        // 2.3 高亮
        if (!StringUtils.isEmptyOrWhitespaceOnly(param.getKeyword())) {
            HighlightBuilder high = new HighlightBuilder();
            high.field("skuTitle");
            high.preTags("<b style='color:red'>");
            high.postTags("</b>");
            sourceBuilder.highlighter(high);
        }


        System.out.println(sourceBuilder.toString());

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    }

    // 聚合
    private SearchRequest buildAggRequest(SearchParam param){
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         *  聚合
         */
        // 3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 3.1 品牌聚合 子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        // 3.2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);
        // 3.2 分类聚合 子聚合
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        // 3.3 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 3.3 属性聚合 子聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));

        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    }

    // 解析响应数据
    private MySearchResult buildSearchResult(SearchResponse search,SearchResponse agg, SearchParam param) {
        MySearchResult mySearchResult = new MySearchResult();
        SearchHits hits = search.getHits();
        // 设置商品
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String source = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(source, SkuEsModel.class);
//                HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
//                String s = skuTitle.getFragments()[0].string();
//                skuEsModel.setSkuTitle(s);
                esModels.add(skuEsModel);
            }
        }
        mySearchResult.setProducts(esModels);
        // 设置属性
        Aggregations aggregations = agg.getAggregations();
        ParsedNested attr_agg = aggregations.get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<MySearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            MySearchResult.AttrVo attrVo = new MySearchResult.AttrVo();
            // 设置属性id
            attrVo.setAttrId(bucket.getKeyAsString());
            // 设置属性名字
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            attrVo.setAttrName(attr_name_agg.getBuckets().get(0).getKeyAsString());
            // 设置属性所有值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> collect = attr_value_agg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValue(collect);
            attrVos.add(attrVo);
        }
        mySearchResult.setAttrs(attrVos);
        // 设置品牌
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        List<MySearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            MySearchResult.BrandVo brandVo = new MySearchResult.BrandVo();
            // 设置品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());
            // 设置品牌名字
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
            // 设置品牌id
            brandVo.setBrandId(String.valueOf(bucket.getKeyAsNumber()));
            brandVos.add(brandVo);
        }
        mySearchResult.setBrands(brandVos);
        // 设置分类
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<MySearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            MySearchResult.CatalogVo catalogVo = new MySearchResult.CatalogVo();
            // 设置catalogId
            catalogVo.setCatalogId(bucket.getKeyAsString());
            // 设置catalogName
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            catalogVo.setCatalogName(catalog_name_agg.getBuckets().get(0).getKeyAsString());

            catalogVos.add(catalogVo);
        }
        mySearchResult.setCatalogs(catalogVos);
        // 设置当前页码
        mySearchResult.setPageNum(param.getPageNum());
        // 设置总记录数
        long total = hits.getTotalHits().value;
        mySearchResult.setTotalCount(total);
        // 设置总页数
        int l = (int) (total % EsConstant.PRODUCT_PAGESIZE == 0 ? total / EsConstant.PRODUCT_PAGESIZE : (total / EsConstant.PRODUCT_PAGESIZE + 1));
        mySearchResult.setTotalPages(l);
        // 设置页码数组
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= l; i++) {
            list.add(i);
        }
        mySearchResult.setPageNav(list);
        // 构建面包屑导航
        List<MySearchResult.Navs> navsList= new ArrayList<>();
        if (param.getAttrs() != null) {
            String attrs = param.getAttrs();
            String[] split = attrs.split(";");
            for (String s : split) {
                MySearchResult.Navs nav = new MySearchResult.Navs();
                String[] s1 = s.split("_");
                R info = productFeignService.info(s1[0]);
                nav.setNavId(s1[0]);
                nav.setNavValue(s1[1]);
                if (info.getCode() == 0) {
                    AttrTo attrTo = JSON.parseObject(JSON.toJSONString(info.get("attr")),AttrTo.class);
                    nav.setNavName(attrTo.getAttrName());
                } else {
                    System.out.println("商品远程调用有问题");
                    nav.setNavName(s1[0]);
                }
                navsList.add(nav);
            }
//            navsList = split.stream().map(attr -> {
//                MySearchResult.Navs nav = new MySearchResult.Navs();
//                String[] s = attr.split("_");
//                R info = productFeignService.info(s[0]);
//                nav.setNavValue(s[1]);
//                if (info.getCode() == 0) {
//                    AttrTo attrTo = JSON.parseObject(JSON.toJSONString(info.get("attr")),AttrTo.class);
//                    nav.setNavName(attrTo.getAttrName());
//                } else {
//                    System.out.println("商品远程调用有问题");
//                    nav.setNavName(s[0]);
//                }
//                return nav;
//            }).collect(Collectors.toList());

            mySearchResult.setNavs(navsList);
        }

        return mySearchResult;
    }
}
